package com.huarun.common.util;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Util {
	// 加密
	public static String getBase64(String str) {
		String s = null;
		byte[] b = str.getBytes(Charset.forName(Constant.CHARSET));
		if (b != null) {
			s = new BASE64Encoder().encode(b);
		}
		return s;
	}

	// 解密
	public static String getFromBase64(String s) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] b = decoder.decodeBuffer(s);
		String result = new String(b, Charset.forName(Constant.CHARSET));
		return result;
	}

	// 加密
	public static String encode(String str) {
		String s = null;
		byte[] b = str.getBytes(Charset.forName(Constant.CHARSET));
		if (b != null) {
			s = new String(Base64.encodeBase64(b), Charset.forName(Constant.CHARSET));
		}
		return s;
	}

	// 解密
	public static String decode(String s) {
		byte[] b = Base64.decodeBase64(s);
		String result = new String(b, Charset.forName(Constant.CHARSET));
		return result;
	}
	
	// 加密
	public static String encode(MultipartFile file) throws IOException {
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(file.getBytes());
	}
}
